package com.aaa.controller;

import com.aaa.entity.Menu;
import com.aaa.entity.MyReturn;
import com.aaa.service.LoginService;
import com.aaa.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2022/6/25 15:37
 * @description：登录控制器
 * @modified By：
 * @version: 1.0
 */
@Controller
public class LoginController extends BaseController {
    @Autowired
    LoginService loginService;
    @Autowired
    MenuService menuService;
    MyReturn myReturn= new MyReturn();
    @RequestMapping("login.do")
    @ResponseBody
    public MyReturn login(@RequestBody Map<String,Object> map, HttpSession session){
        boolean checkUser = loginService.checkUser(map);
        try {
            //休眠10秒
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(checkUser){
            //登录成功之前，增强处理，将登录名保存到session中
            Map<String, Object> user = loginService.findUserInfoByName(map);
            //清除密码和盐值
            user.remove("password");
            user.remove("salt");
            session.setAttribute("user",user);
            //登录成功之前，增强处理，将登录用户对应的菜单保存到session中
            Map<String, List<Menu>> menuMap = menuService.findMenuByUsername(map.get("username").toString());
            session.setAttribute("menuMap",menuMap);
            //登录成功
            return  super.getSuccessResult(myReturn);
        }
        return  super.getLoginFailResult(myReturn);
    }

    @RequestMapping("logout.do")
    public  String logout( HttpSession session){
        //session失效
        session.invalidate();
        //跳转到登录页面
        return "redirect:/login.jsp";
    }
}
